const { promisify } = require("util");
const request = require('request');
const postPromise = promisify(request.post);
const getPromise = promisify(request.get);

class sendRequest{
    /**
     * 
     * @param {*} param 
     * @param {*} headers 
     * @param {*} timeout 
     * @returns 
     */
     async post(url,param,timeout = 8000,headers = {"content-type": "application/x-www-form-urlencoded"}){
        const resp = await postPromise({
            url: url,
            form: param,
            headers:headers,
            rejectUnauthorized: false,
            timeout: timeout,
        });
        if (resp.statusCode != 200) {
            return (`状态码：${resp.statusCode}，内容：${resp.body}`);
        }
        return resp.body;
    }

    /**
     * 
     * @param {*} url 
     * @param {*} headers 
     * @param {*} timeout 
     * @returns 
     */
    async get(url,timeout = 8000,headers = {"content-type": "application/x-www-form-urlencoded"}){
        const resp = await getPromise({
            url: url,
            headers:headers,
            rejectUnauthorized: false,
            timeout: timeout,
        });
        if (resp.statusCode != 200) {
            throw new Error(`状态码：${resp.statusCode}，内容：${resp.body}`);
        }
        return resp.body;
    }
}

module.exports = new sendRequest();
